package com.example.daxiguaforharmony.utils;

import ohos.app.Context;
import ohos.data.distributed.common.*;
import ohos.data.distributed.device.DeviceFilterStrategy;
import ohos.data.distributed.device.DeviceInfo;
import ohos.data.distributed.device.DeviceKvStore;
import ohos.data.distributed.user.SingleKvStore;

import java.util.ArrayList;
import java.util.List;

/**
 * 设备协同分布式数据库管理类
 */
public class DbsKvManager {
    //private static DbsKvManager instance;
    private volatile static DbsKvManager singleton;

//    public static synchronized DbsKvManager getInstance(Context context) {
//        if (instance == null) {
//            instance = new DbsKvManager(context);
//        }
//        return instance;
//    }

    public static DbsKvManager getDbsKvManager(Context context) {
        if (singleton == null) {
            synchronized (DbsKvManager.class) {
                if (singleton == null) {
                    singleton = new DbsKvManager( context);
                }
            }
        }
        return singleton;
    }

    DeviceKvStore deviceKvStore;
    KvManager kvManager;
    String DeviceId;

    /**
     * 配置构造设备协同分布式存储管理类
     */
    public DbsKvManager(Context context) {
        try{
            System.out.println("创建db开始======");
            //Context context = this.Context();
            KvManagerConfig config = new KvManagerConfig(context);
            kvManager = KvManagerFactory.getInstance().createKvManager(config);
            DeviceId = kvManager.getLocalDeviceInfo().getId();
            System.out.println("DbKvManager DeviceId="+DeviceId);
            Options CREATE = new Options();
            CREATE.setCreateIfMissing(true).setEncrypt(false).setKvStoreType(KvStoreType.DEVICE_COLLABORATION);//设置数据库不存在时创建
            String storeID = "daxiguaforharmony";
            deviceKvStore = kvManager.getKvStore(CREATE, storeID);

            System.out.println("创建db end======");
        }
        catch (Exception err)
        {
            System.out.println("创建db 失败=====err="+err.getMessage());
        }
    }

    public void init(Context context) {
        try{
            System.out.println("创建db开始======");
            //Context context = this.Context();
            KvManagerConfig config = new KvManagerConfig(context);
            kvManager = KvManagerFactory.getInstance().createKvManager(config);
            Options CREATE = new Options();
            CREATE.setCreateIfMissing(true).setEncrypt(false).setKvStoreType(KvStoreType.DEVICE_COLLABORATION);//设置数据库不存在时创建
            String storeID = "daxiguaforharmony";
            deviceKvStore = kvManager.getKvStore(CREATE, storeID);
            DeviceId = kvManager.getLocalDeviceInfo().getId();
            System.out.println("创建db end======");
        }
        catch (Exception err)
        {
            System.out.println("创建db 失败=====err="+err.getMessage());
        }
    }

    /**
     * 获取当前设备id
     * @return
     */
    public String getDeviceId()
    {
        //String deviceId = KvManagerFactory.getInstance().createKvManager(new KvManagerConfig(this)).getLocalDeviceInfo().getId();//获取当前设备id
        String deviceId = DeviceId;//获取当前设备id
        return deviceId;
    }

    /**
     * 写入数据
     *
     * @param key
     * @param value
     * @return
     */
    public void write(String key, String value) {
        try{
            if(key.isEmpty())
            {
                throw new Exception("key 不能为空");
            }
            System.out.println("开始写入数据====" + key + "===" + value);
            deviceKvStore.putString(key, value);
            System.out.println("结束写入数据====" + key);
        }
        catch (Exception err)
        {
            System.out.println("写入失败了!!! err==="+err.getMessage());
        }



    }

    /**
     * 读取数据
     *
     * @param key
     * @return
     */
    public String read(String deviceId,String key) {
        try {
            System.out.println("开始读取数据====" + key);
            String value = deviceKvStore.getString(deviceId,key);
            System.out.println("结束读取数据====" + key);
            return value;
        }
        catch (Exception err)
        {
            try {
                deviceKvStore.putString(key, "0");
                System.out.println("读取err===="+err.getMessage());
                return "";
            }
            catch (Exception err2)
            {
                //singleKvStore.putString(key, "0");
                System.out.println("读取err===="+err2.getMessage());
                return "";
            }
        }


    }

    public List<String> getDeviceList()
    {
        List<String> deviceIdList = new ArrayList<>();
        try {
            System.out.println("获取已连接的设备列表 getDeviceList ====");
            List<DeviceInfo> deviceInfoList = kvManager.getConnectedDevicesInfo(DeviceFilterStrategy.NO_FILTER);

            if(deviceInfoList.size()>0)
            {
                for (DeviceInfo deviceInfo : deviceInfoList) {
                    deviceIdList.add(deviceInfo.getId());
                }
            }
            return deviceIdList;

        }
        catch (Exception err)
        {
            err.printStackTrace();
            System.out.println("getDeviceList err===="+err.getClass()+"=="+err.getMessage());
            return deviceIdList;
        }
    }

    /**
     * 同步数据到其他设备。
     * 1. 获取已连接的设备列表。
     * 2. 选择同步方式进行数据同步。
     * 以下为单版本分布式数据库进行数据同步的代码示例，其中同步方式为PUSH_ONLY：
     */
    public void syncDeviceData() {
        try {
            System.out.println("获取已连接的设备列表 syncDeviceData ====");
            List<DeviceInfo> deviceInfoList = kvManager.getConnectedDevicesInfo(DeviceFilterStrategy.NO_FILTER);
            List<String> deviceIdList = new ArrayList<>();
            if(deviceInfoList.size()>0)
            {
                for (DeviceInfo deviceInfo : deviceInfoList) {
                    deviceIdList.add(deviceInfo.getId());
                }
                deviceKvStore.sync(deviceIdList, SyncMode.PUSH_ONLY);//PUSH_ONLY
            }

        }
        catch (Exception err)
        {
            err.printStackTrace();
            System.out.println("syncDeviceData err===="+err.getClass()+"=="+err.getMessage());
        }

    }

    /**
     * 订阅单版本分布式数据库所有（本地及远端）数据变化通知
     */
    public void subscribe()
    {
        KvStoreObserver kvStoreObserverClient = new KvStoreObserverClient();
        deviceKvStore.subscribe(SubscribeType.SUBSCRIBE_TYPE_ALL, kvStoreObserverClient);
    }


    /**
     * 关闭数据库
     */
    public void close()
    {
        kvManager.closeKvStore(deviceKvStore);
    }

    /**
     * 删除Db
     * @param storeID
     */
    public void deleteDb(String storeID)
    {
        kvManager.deleteKvStore(storeID);
    }



}